import Vue from 'vue'
import { getUserPermissions } from '../common/js/cache'

Vue.directive('permission', {
  inserted(el, binging, _vnode) {
    const { value } = binging
    const userPermissions = getUserPermissions()
    if (value && value instanceof Array && value.length) {
      const hasPermission = userPermissions.some(item => {
        return value.includes(item)
      })
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(
        `need permission! Like v-permission="['insert','editor']"`
      )
    }
  }
})

Vue.directive('click-outside', {
  bind(el, binding) {
    function clickHandler(e) {
      if (el.contains(e.target)) {
        return false
      }
      if (binding.expression) {
        binding.value(e)
      }
    }
    el.__vueClickOutside__ = clickHandler
    document.addEventListener('click', clickHandler)
  },
  unbind(el) {
    document.removeEventListener('click', el.__vueClickOutside__)
    delete el.__vueClickOutside__
  }
})
